import cv2 as cv


def local_threshold(img):
    gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    binary = cv.adaptiveThreshold(gray, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 25, 10)
    cv.imshow("binary", binary)


def show_img(img):
    height, weight, channels = img.shape
    for x in range(weight):
        for y in range(height):
            try:
                r, g, b = img[x, y]
                if (r / 3 + g / 3 + b / 3) < 100:
                    write_file("1")
                else:
                    write_file("0")
            except Exception as e:
                continue
        write_file("\n")


def write_file(text):
    with open('test.txt', 'a') as f:
        f.write(text)


if __name__ == "__main__":
    src = cv.imread("123.jpg")
    cv.namedWindow("input img", cv.WINDOW_AUTOSIZE)
    cv.imshow("input img", src)
    local_threshold(src)
    # show_img(src)
    cv.waitKey(0)
    cv.destroyAllWindows()
